<?php

ob_start("ob_gzhandler");
if (!isset($_SESSION)) {
    session_start();
}
require('../../Smarty/libs/Smarty.class.php');
include_once 'API/APIObject.php';
include_once 'API/Utils.php';
$smarty = new Smarty;

$smarty->setTemplateDir('./smarty/templates/');
$smarty->setCompileDir('./smarty/templates_c/');
$smarty->setConfigDir('./smarty/configs/');
$smarty->setCacheDir('./smarty/cache/');
$smarty->setCaching(true);      // activating caching of the pages
$smarty->force_compile = true;  // forcing compiling the templates for ajax

$continue = true;
$amenities = array();
$hotelArray = array();
$output = "";

// POST DATA
if (isset($_POST)) {
    if (isset($_POST["hotelId"]) && $continue == true) {
        $hotelId = $_POST["hotelId"];
    } else {
        $continue = false;
    }
    if (isset($_POST["service"]) && $continue == true) {
        $service = $_POST["service"];
    } else {
        $continue = false;
    }
    if (isset($_POST["rateCode"])) {
        $rateCode = $_POST["rateCode"];
    }
    if (isset($_POST["roomTypeCode"])) {
        $roomTypeCode = $_POST["roomTypeCode"];
    }
    if (isset($_POST["rateKey"]) && $continue == true) {
        $rateKey = $_POST["rateKey"];
    }
    if (isset($_POST["thumbnailImage"]) && $continue == true) {
        $hotelImage = $_POST["thumbnailImage"];
    }
}
if (isset($_SESSION)) {
    if (isset($_SESSION["search"]["checkIn"])) {
        $checkIn = $_SESSION["search"]["checkIn"];
    } else {
        $continue = FALSE;
    }
    if (isset($_SESSION["search"]["checkOut"])) {
        $checkOut = $_SESSION["search"]["checkOut"];
    } else {
        $continue = FALSE;
    }
    if (isset($_SESSION["search"]["roomCount"])) {
        $roomCount = $_SESSION["search"]["roomCount"];
    } else {
        $continue = FALSE;
    }
    if (isset($_SESSION["rooms"])) {
        $roomsData = $_SESSION["rooms"];
    }
} else {
    $continue = FALSE;
}

$api = new APIObject();
$filter = new Filter();

$smarty->assign("server", 'bookingPage.php');
$filter->supplierType = "E";
$filter->RoomGroup = new RoomGroup(NULL, 1);

for ($i = 1; $i <= $roomCount; $i++) {
    $filter->RoomGroup->Room[$i] = new Room();
    $filter->RoomGroup->Room[$i]->numberOfAdults = $roomsData[$i]['adults'];
    $splitResult = explode(",", $roomsData[$i]['ages_string']);
    for ($j = 0; $j < $roomsData[$i]['children']; $j++) {
        $filter->RoomGroup->Room[$i]->childAges = ($splitResult) ? $splitResult[$j] : "";
    }
}

// HARDCODED DATA FOR HOTEL INFORMATION
$options = "HOTEL_SUMMARY,HOTEL_DETAILS,PROPERTY_AMENITIES";

// HARDCODED DATA FOR ROOM AVAILABILITY
$numberOfBedRooms = NULL;
$supplierType = "E";

if (!isset($rateKey)) {
    $rateKey = NULL;
}
if (!isset($roomTypeCode) || !isset($rateCode)) {
    $roomTypeCode = NULL;
    $rateCode = NULL;
}
$includeDetails = FALSE;
$includeRoomImages = FALSE;
$optionsAvail = "ROOM_TYPES";
$roomGroup = $filter->RoomGroup;


if ($service == "INFO") {
// HOTEL INFORMATION CALL
/*
    $hotelResponse = $api->GetHotelInformation($hotelId, $options);
    $hotelSummary = $hotelResponse->HotelSummary;
    $hotelDetails = $hotelResponse->HotelDetails;
    $propertyAmenities = $hotelResponse->PropertyAmenities;
    $index = 1;
    foreach ($propertyAmenities->PropertyAmenity as $value) {
        $amenities[$index]["amenity"] = $value->amenity;
        $amenities[$index++]["amenityId"] = $value->amenityId;
    }
    $hotelArray = array(
        "hotelPolicy" => $hotelDetails->hotelPolicy,
        "checkInInstructions" => $hotelDetails->checkInInstructions,
        "roomInformation" => $hotelDetails->roomInformation,
        "propertyDescription" => html_entity_decode($hotelDetails->propertyDescription),
        "areaInformation" => $hotelDetails->areaInformation,
        "checkInTime" => $hotelDetails->checkInTime,
        "checkOutTime" => $hotelDetails->checkOutTime,
        "id" => $hotelSummary->hotelId,
        "hotelName" => $hotelSummary->name,
        "supplierType" => "E",
        "propertyAmenities" => $amenities,
        "propertyCategory" => $hotelSummary->propertyCategory
    );
	*/
	mysql_connect("localhost:3306", "root", "expedia") or die("Unable to connect to MySQL " . mysql_error());
    @mysql_select_db("eanprod") or die("Unable to select database " . mysql_error());
	
	$qstring = "SELECT 'E' AS supplierType, hotels.EANHotelID AS id, hotels.PropertyCategory AS propertyCategory, propdesc.PropertyDescription AS propertyDescription, policy.PolicyDescription AS hotelPolicy, hotels.CheckInTime AS checkInTime, hotels.CheckOutTime AS checkOutTime FROM activepropertylist AS hotels LEFT JOIN propertydescriptionlist AS propdesc ON hotels.EANHotelID = propdesc.EANHotelID LEFT JOIN policydescriptionlist AS policy ON hotels.EANHotelID = policy.EANHotelID WHERE hotels.EANHotelID = $hotelId";
	
	$result = mysql_query($qstring) or die(mysql_error());
	$info = mysql_fetch_array($result, MYSQL_ASSOC);
	
	$qstring2 = "SELECT link.AttributeId AS amenityId, attr.AttributeDesc AS amenity, link.appendTxt AS append FROM propertyattributelink AS link INNER JOIN attributelist AS attr ON link.AttributeID = attr.AttributeID WHERE attr.Type = 'PropertyAmenity' AND link.EANHotelID =  $hotelId";
	
	$result2 = mysql_query($qstring2) or die(mysql_error());
	$i = 0;
	while($amenity = mysql_fetch_array($result2, MYSQL_ASSOC)){
		$amenities[$i]["amenity"] = html_entity_decode($amenity["amenity"]);
		$amenities[$i]["amenityId"] = $amenity["amenityId"];
		$amenities[$i++]["append"] = $amenity["append"];
	}
	
	$info["propertyAmenities"] = $amenities;
	
    $smarty->assign("hotel", $info);
    $output = $smarty->fetch('hotel_details.tpl');
} elseif ($service == "AVAIL") {
    // ROOM AVAILABILITTY CALL
    $roomAvail = $api->GetRoomAvailability(
            $hotelId, $checkIn, $checkOut, $numberOfBedRooms, $supplierType, $rateKey, $rateCode, $roomTypeCode, $includeDetails, $includeRoomImages, $optionsAvail, $roomGroup);
    if (is_array($roomAvail->HotelRoomResponse)) {
        $hotelRoomsRes = $roomAvail->HotelRoomResponse;
    } else {
        $hotelRoomsRes = array($roomAvail->HotelRoomResponse);
    }
    $positions = array();
    $cur = 0;
    foreach ($hotelRoomsRes as $index => $value) {
        $nightRates = 0;

        $rateInfo = isset($value->RateInfos->RateInfo) ? $value->RateInfos->RateInfo : "";

        if ($rateInfo != "") {
            if (is_array($rateInfo->ChargeableRateInfo->NightlyRatesPerRoom->NightlyRate)) {
                $nightlyRate = $rateInfo->ChargeableRateInfo->NightlyRatesPerRoom->NightlyRate;
            } else {
                $nightlyRate = array($rateInfo->ChargeableRateInfo->NightlyRatesPerRoom->NightlyRate);
            }
            foreach ($nightlyRate as $rate) {
                $nightRates += $rate->{"@rate"};
            }
        }

        $hotelRooms[$index] = array(
            "rateCode" => isset($value->rateCode) ? $value->rateCode : "",
            "roomTypeCode" => isset($value->RoomType->{"@roomCode"}) ? $value->RoomType->{"@roomCode"} : "",
            "roomTypeDescription" => isset($value->RoomType->descriptionLong) ? $value->RoomType->descriptionLong : "",
            "roomTypeString" => isset($value->RoomType->description) ? $value->RoomType->description : "",
            "minGuestAge" => isset($value->minGuestAge) ? $value->minGuestAge : "",
            "nonRefundable" => isset($value->nonRefundable) ? $value->nonRefundable : "",
            "promoId" => isset($value->promoId) ? $value->promoId : "",
            "promoDescription" => isset($value->promoDescription) ? $value->promoDescription : "",
            "currentAllotment" => isset($value->currentAllotment) ? $value->currentAllotment : "",
            "rateInfo" => array(
                "averageRate" => isset($rateInfo->ChargeableRateInfo->{"@averageRate"}) ? $rateInfo->ChargeableRateInfo->{"@averageRate"} : "",
                "total" => isset($rateInfo->ChargeableRateInfo->{"@total"}) ? $rateInfo->ChargeableRateInfo->{"@total"} : "",
                "currencyCode" => isset($rateInfo->ChargeableRateInfo->{"@currencyCode"}) ? $rateInfo->ChargeableRateInfo->{"@currencyCode"} : "",
                "surchargeTotal" => isset($rateInfo->ChargeableRateInfo->{"@surchargeTotal"}) ? $rateInfo->ChargeableRateInfo->{"@surchargeTotal"} : "",
                "nightlyRatesTotal" => isset($nightRates) ? $nightRates : "",
                "salesTax" => "",
                "hotelOccupancyTax" => ""
            ),
            "noData" => ($rateInfo == "") ? true : false
        );
    }

    $hotelArray = array(
        "rateKey" => isset($roomAvail->rateKey) ? $roomAvail->rateKey : "",
        "id" => isset($roomAvail->hotelId) ? $roomAvail->hotelId : "",
        "checkInInstructions" => isset($roomAvail->checkInInstructions) ? $roomAvail->checkInInstructions : "",
        "supplierType" => "E",
        "checkin" => $checkIn,
        "checkout" => $checkOut,
        "thumbnailUrl" => $hotelImage,
        "hotelName" => $roomAvail->hotelName,
        "room" => $hotelRooms
    );

    $smarty->assign("hotel", $hotelArray);
    $output = $smarty->fetch('room_details.tpl');
} elseif ($service == "CANCEL") {
    $rateKey = $_POST["rateKey"];
    $rateCode = $_POST["rateCode"];
    $roomTypeCode = $_POST["roomTypeCode"];
    $roomAvail = $api->GetRoomAvailability(
            $hotelId, $checkIn, $checkOut, $numberOfBedRooms, $supplierType, $rateKey, $rateCode, $roomTypeCode, $includeDetails, $includeRoomImages, $optionsAvail, $roomGroup);
    try {
        $cancellationPolicy = isset($roomAvail->HotelRoomResponse->cancellationPolicy) ? $roomAvail->HotelRoomResponse->cancellationPolicy : "Cancellation policy was not found ! Please do not book this room. If you try to book the room, you are doing it on your own risk.";
        $smokingPreferences = isset($roomAvail->HotelRoomResponse->smokingPreferences) ? $roomAvail->HotelRoomResponse->smokingPreferences : "";
        $smarty->assign("cancellationPolicy", $cancellationPolicy);
        $smarty->assign("smokingPreferences", $smokingPreferences);
        $_SESSION["cancellationPolicy"] = $cancellationPolicy;
        $_SESSION["smokingPreferences"] = $smokingPreferences;
        $_SESSION["averageRate"] = isset($roomAvail->HotelRoomResponse->RateInfos->RateInfo->ChargeableRateInfo->NightlyRatesPerRoom->NightlyRate->{"@rate"}) ? $roomAvail->HotelRoomResponse->RateInfos->RateInfo->ChargeableRateInfo->NightlyRatesPerRoom->NightlyRate->{"@rate"} : "Not Available";
        //var_dump($roomAvail);

        $smarty->assign("id", $hotelId);
        $smarty->assign("roomTypeCode", $roomTypeCode);
        $output = $smarty->fetch('cancelation_policy.tpl');
    } catch (Exception $exp) {
        $output = "";
    }
} elseif ($service == "IMG") {
    // HOTEL INFORMATION CALL
    // HARDCODED DATA FOR HOTEL INFORMATION
	$imageList = array();
	$i = 0;
	
	mysql_connect("localhost:3306", "root", "expedia") or die("Unable to connect to MySQL " . mysql_error());
    @mysql_select_db("eanprod") or die("Unable to select database " . mysql_error());
	
	$qstring = "SELECT hl.Caption AS caption, hl.EANHotelID AS id, hl.ThumbnailURL AS thumbnailUrl, hl.URL AS url FROM hotelimagelist AS hl WHERE EANHotelID = $hotelId";
	$result = mysql_query($qstring) or die(mysql_error());

    while($image = mysql_fetch_array($result, MYSQL_ASSOC)){
		$imageList[$i++] = $image;
	}
	
	$imageCount = count($imageList);
	
	/*
    $options = "HOTEL_IMAGES";
    $hotelArray = array();
    $hotelResponse = $api->GetHotelInformation($hotelId, $options);
    $hotelImages = $hotelResponse->HotelImages->HotelImage;
    $imageCount = count($hotelImages);
    if ($imageCount == 1) {
        $hotelImages = array($hotelResponse->HotelImages->HotelImage);
    } else if($imageCount == 0){
        $hotelImages = array();
    } */
	/*
    foreach ($hotelImages as $key => $value) {
        $hotelArray[$key] = array(
            "thumbnailUrl" => substr_replace($value->thumbnailUrl, "t", -5, 1),
            "url" => $value->url,
            "id" => $hotelId,
            "nr_picture" => $key,
            "caption" => ""
        );
    }*/
    $smarty->assign("imageCount", $imageCount);
    $smarty->assign("hotelId", $hotelId);
    $smarty->assign("hotel", $imageList);
    $output = $smarty->fetch('hotel_gallery.tpl');
}

print_r($output);
?>